(ns ura.data.LogData
  (:require
   [taoensso.telemere :as t :refer [log!]]
   [ura.data.Data :as dt :refer [execute executeSql checkDataNull upcaseKey]]
   [tick.core :as tk]
   )
  (:use tupelo.core)
  )

(import
 org.apache.poi.hssf.usermodel.HSSFWorkbook
 )


(defn getLogModels []
  (let [models (dt/execute ["select distinct(MODEL_NAME) from log_data"])]
    (t/log! {:data models} "get model result: ")
    (mapv (fn [v]
            {:id (:model_name v) :label (:model_name v)}
            )
          models
          )
    )
  )


(defn queryLog [params]
  (log! ["query log data: " params])
  (let [level (:level params)
        username (:username params)
        model (:model params)
        message (:message params)
        starDate (:startDate params)
        endDate (:endDate params)
        ]
    (executeSql {:select [:*]
                 :from :LOG_DATA
                 :where [:and
                         (when (checkDataNull level) [:= :LEVEL level])
                         (when (checkDataNull username) [:like :USERNAME (str "%" username "%")])
                         (when (checkDataNull model) [:= :MODEL_NAME model])
                         (when (checkDataNull message) [:like :MESSAGE (str "%" message "%")])
                         ]
                 })
    )
  )


(defn saveLog [logData]
  (t/log! ["get saveLog request: " logData])
  (let [logDate (tk/format (tk/formatter "yyyy-MM-dd HH:mm:ss") (tk/date-time))
        data1 (select-keys logData [:level :model_name :username :message :data])
        data (upcaseKey (merge data1 {:ID :LOG_DATA_SEQ.nextval :LOG_DATE logDate}))
        ]
    (executeSql {:insert-into [:LOG_DATA]
                    :values [data]
                    })
    )
  )

(defn exportLog []
  (t/log! "export data")
  (let [book     (new HSSFWorkbook)
        sheet    (.createSheet book "日志数据")

        head     ["日期" "模块" "用户" "级别" "消息"]
        headrow  (.createRow sheet 0)

        data     (queryLog nil)
        len      (count data)
        
        time     (tk/format (tk/formatter "yyyyMMdd-HHmmss") (tk/date-time))
        filepath "./web/export/"
        filename (str "log-" time ".xlsx")
        file     (str filepath filename)
        out      (new java.io.FileOutputStream (new java.io.File file))
        ]
    
    (doseq [ i (range 0 5)
            :let [v (head i)]
            ]
      (.setCellValue (.createCell headrow i) v)
      )
    
    (doseq [i (range len)
            :let [dt (nth data i)
                  row  (.createRow sheet (+ i 1))
                  ]]
      (.setCellValue (.createCell row 0) (str (:log_date dt)))
      (.setCellValue (.createCell row 1) (:model dt))
      (.setCellValue (.createCell row 2) (:username dt))
      (.setCellValue (.createCell row 3) (:level dt))
      (.setCellValue (.createCell row 4) (:message dt))
      )
    
    (.write book out)
    (.close out)
    (t/log! {:data file} "generated export file")
    [file filename]
    )
  )
